<template>
  <view class="">
    <!-- 课程主图和基本信息 -->
    <course-header :course="course"></course-header>

    <view class="course-details" :style="{height:`${pageHeight}px`}">
      <tab-bar :tabs="tabs" @changeTab="changeTab" :tabIndex="tabIndex"></tab-bar>
      <swiper class="swiper-box" :duration="300" :current="tabIndex" circular @change="slideTab">
        <swiper-item v-for="(item,index) in tabs" :key="item.id">
          <scroll-view class="scroll-box" :scroll-y="enableScroll" @scrolltoupper="scrolltoupper" :upper-threshold="0">
            <view class="details-info">
              <course-info :detailUrls="course.detailUrls" v-if="index === 0"></course-info>
              <course-dir :chapterList="chapterList" v-if="index === 1" :isBuy="isBuy" @playVideo="playVideo"
                :activeObj="activeObj">
              </course-dir>
              <course-comment :commentList="commentList" v-if="index === 2"></course-comment>
              <course-group  :groupList="groupList" v-if="index === 3"></course-group>
            </view>
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>

    <buttom-btn :btnText="isBuy || course.isFree ? '立即观看' :'立即购买'" @clickBottom="clickBottom"></buttom-btn>

    <!-- #ifdef APP-PLUS -->
    <share ref="shareRef" :shareData="course"></share>
    <!-- #endif -->

    <!-- 试看组件 -->
    <view class="video-box mask" @touchmove.stop.prevent="()=>{}" v-if="state.videoUrl" @click="closeVideo">
      <view class="name">
        <text>{{state.serialNumber}}&nbsp;&nbsp;{{state.videoText}}</text>
        <text class="iconfont icon-close" @click="closeVideo"></text>
      </view>
      <video id="playVideo" class="video" :src="state.videoUrl"></video>
    </view>


  </view>
</template>

<script setup lang="ts">
  import {
    onLoad,
    onReachBottom,
    onReady,
    onPageScroll,
    onNavigationBarButtonTap,
    onShareAppMessage
  } from '@dcloudio/uni-app'
  import {
    reactive,
    ref,
    getCurrentInstance,
    nextTick
  } from 'vue'
  import courseHeader from './components/course-header.vue'
  import courseInfo from './components/course-info.vue'
  import courseDir from './components/course-dir.vue'
  import courseComment from './components/course-comment.vue'
  import courseGroup from './components/course-group.vue'
  import tabBar from '@/components/common/tab-bar.vue'
  import buttomBtn from '@/components/common/buttom-btn.vue'
  import api from '@/api/course.js'

  const {
    proxy
  } = getCurrentInstance()
  const tabs = ref([{
      id: 1,
      name: '详情'
    },
    {
      id: 2,
      name: '章节'
    },
    {
      id: 3,
      name: '评论'
    },
    {
      id: 4,
      name: '套餐'
    }
  ])
  const tabIndex = ref(0)
  const pageHeight = ref(0)
  const statusNavHeight = ref(0)
  const enableScroll = ref(false)
  const detailToTop = ref(0)
  const id = ref(0)
  const course = ref([])
  const chapterList = ref([])
  const commentList = ref([])
  const groupList = ref([])
  const shareRef = ref()
  const isBuy = ref(false)
  let state = reactive({
    videoUrl: null, //试看视频地址
    videoText: "", //试看视频标题
    videoContext: null, //播放实例
    serialNumber: 0
  })
  let activeObj = reactive({
    chapterIndex: -1,
    sectionIndex: -1
  })
  // 点击tab事件
  const changeTab = (index) => {
    tabIndex.value = index
  }
  // 滑动触发事件
  const slideTab = (e) => {
    tabIndex.value = e.detail.current

    uni.pageScrollTo({
      scrollTop: detailToTop.value,
      duration: 300
    })
  }

  // 监听scroll-view是否滑动到顶部事件
  const scrolltoupper = () => {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
    enableScroll.value = false
  }
  // 获取当前手机页面视口高度
  const getPageHeight = (e) => {
    const res = uni.getSystemInfoSync()
    const system = res.platform
    const statusBarHeight = res.statusBarHeight
    if (system === 'android') {
      statusNavHeight.value = statusBarHeight + 48
    } else if (system === 'ios') {
      statusNavHeight.value = statusBarHeight + 44
    }
    pageHeight.value = res.screenHeight - statusNavHeight.value
  }
  onLoad((option) => {
    getPageHeight()

    // 禁用app端点击状态栏回到顶部
    // #ifdef APP-PLUS
    let webView = proxy.$scope.$getAppWebview()
    webView.setStyle({
      "scrollToTop": false
    })
    // #endif

    id.value = option.id
    getCourseDetailsData()
  })

  // 监听页面滚动事件
  onPageScroll((e) => {
    if (detailToTop.value - statusNavHeight.value <= e.scrollTop) {
      enableScroll.value = true
      return
    }
    if (enableScroll.value && e.scrollTop < detailToTop.value) {
      enableScroll.value = false
    }

  })
  //监听手机原生按钮点击事件(右上角分享按钮)
  // #ifdef APP-PLUS
  onNavigationBarButtonTap((e) => {
    if (e.type == 'share') {
      shareRef.value.showHandler()
    }
  })
  // #endif

  // 监听页面到到底部事件
  onReachBottom(() => {
    enableScroll.value = true
  })
  onReady(() => {
    // 获取详情到顶部距离的高度
    let view = uni.createSelectorQuery().in(proxy).select(".course-details")

    view.fields({
      rect: true
    }, data => {
      detailToTop.value = data.top
    }).exec()
    //获取播放实例
    state.videoContext = uni.createVideoContext('playVideo', proxy)
  })

  // 获取数据
  const getCourseDetailsData = async () => {
    // 判断是否购买
    isBuy.value = proxy.$utils.isLogin({
      nav: false
    }) && (await api.getCourseIsBuy({
      userId: 1,
      courseId: id.value
    })).data
    const courseInfoRes = await api.getCourseDetail(id.value)
    const courseSectionRes = await api.getCourseSection(id.value)
    const courseCommentRes = await api.getCourseComment(id.value)
    const coursePackageRes = await api.getCoursePackage(id.value)

    course.value = courseInfoRes.data
    chapterList.value = courseSectionRes.data
    commentList.value = courseCommentRes.data
    groupList.value = coursePackageRes.data
    uni.setNavigationBarTitle({
      title: course.value.title
    })

  }

  // 点击视频
  let playVideo = (itemInfo) => {
    if (isBuy.value) {
      //判断是否购买课程，购买了课程就进入观看页面(非试看组件)
      // sectionRef.value.actSect=itemInfo.section.name	//修改子组件中数据
      proxy.navTo('/pages/course/course-play?id=' + state.id)
      return
    }
    // 播放的url地址
    state.videoUrl = itemInfo.section.videoUrl
    // 播放的章节数
    state.serialNumber = (itemInfo.chapterIndex + 1) + "-" + (itemInfo.sectionIndex + 1)
    // 播放的章节名字
    state.videoText = itemInfo.section.name
    // 判断激活点击的章节进行高亮展示
    activeObj.chapterIndex = itemInfo.chapterIndex
    activeObj.sectionIndex = itemInfo.sectionIndex
    nextTick(() => {
      state.videoContext.play() //手动播放
    })
  }
  // 关闭试看组件
  let closeVideo = () => {
    state.videoUrl = null
  }

  // 点击底部按钮触发事件
  const clickBottom = () => {
    // 已购买或者免费课，跳转到视频播放页
    if (isBuy.value || course.value.isFree) {
      proxy.navTo(`/pages/course/course-play?id=${id.value}`)
    } else {
      // #ifndef APP-PLUS
      proxy.navTo(`/pages/order/confirm-buy?course=` + encodeURIComponent(JSON.stringify(course.value)))
      // #endif
      // #ifdef APP-PLUS
      proxy.navTo(`/pages/order/confirm-buy?id=${id.value}`)
      // #endif
    }
  }

  // 小程序分享
  onShareAppMessage((res) => {
    return {
      title: course.value.title,
      path: proxy.$utils.routePath()
    }
  })
</script>

<style scoped lang="scss">
  .course-details {
    overflow: hidden;

    .swiper-box,
    .scroll-box {
      height: 100%;
    }

    .details-info {
      padding-bottom: 180rpx;
    }
  }


  .video-box {
    z-index: 100;
    text-align: center;

    .name {
      color: #FFFFFF;
      position: relative;
      top: 380rpx;
      /* #ifdef MP */
      top: 300rpx;
      /* #endif */
      font-size: 38rpx;
      font-weight: bold;
    }

    .icon-close {
      margin-left: 20rpx;
    }

    .video {
      width: 750rpx;
      height: 420rpx;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

  }
</style>
